<script setup lang="ts">
	import { ref, onMounted } from "vue";
	import { formRules } from "./utils/rule";
	import { FormProps } from "./utils/types";
	import ReCol from "@/components/ReCol";
  import dayjs from 'dayjs';
  import { useRouter } from "vue-router"
  import {
    projectSelectApi
  } from "@/api/projectApi";
  import {
    userSelectApi
  } from "@/api/user";
  import {
    partSelectApi,
    supplierSelectApi,
    productSelectApi,
    companySelectApi,
    categorySelectApi
  } from "@/api/quotedPriceApi";
  import { storeListApi } from "@/api/purchaseOrderApi"
  const expandColumns: TableColumnList = [
    { label: "产品名称", prop: "productName", minWidth: 150, formatter:(row: any)=> {
    	return row.productName || '--'
    }},
    { label: "产品编号", prop: "productNo", minWidth: 150, formatter:(row: any)=> {
    	return row.productNo || '--'
    }},
    { label: "规格", prop: "productSpec", minWidth: 150, formatter:(row: any)=> {
    	return row.productSpec || '--'
    }},
    { label: "单位", prop: "productUnit", minWidth: 80, formatter:(row: any)=> {
    	return row.productUnit || '--'
    }},
    { label: "数量", prop: "number", minWidth: 120, formatter:(row: any)=> {
    	return row.number*1 || '--'
    }},
    { label: "产品单价", prop: "price", minWidth: 140, formatter:(row: any)=> {
    	return row.price*1 || '--'
    }},
    { label: "总金额", prop: "amount", minWidth: 140, formatter:(row: any)=> {
    	return row.amount*1 || '--'
    }},
    { label: "分类", prop: "category", minWidth: 100, formatter:(row: any)=> {
    	return row.category?.name || '--'
    }},
    { label: "项目", prop: "projectName", minWidth: 150, formatter:(row: any)=> {
    	return row.project?.projectName || '--'
    }},

    { label: "仓库", prop: "store", minWidth: 150, formatter:(row: any)=> {
    	return row.store?.name || '--'
    }},
    { label: "设备", prop: "parts", minWidth: 150, formatter:(row: any)=> {
      let str = [];
      if(row.parts && row.parts['1']) {
        for (let item of row?.parts['1']) {
          str.push(item.deviceName)
        }
      }
    	return str.join() || '--'
    }},
    { label: "配件", prop: "parts", minWidth: 150, formatter:(row: any)=> {
      let str = [];
      if(row.parts) {
        for (let item of row?.parts['2']) {
          str.push(item.partName)
        }
      }
    	return str.join() || '--'
    }},
    { label: "备注", prop: "remarks", minWidth: 120, formatter:(row: any)=> {
    	return row.remarks || '--'
    }},
  ];
	const props = withDefaults(defineProps<FormProps>(), {
		formInline: () => ({
			title: "",
			status: 0,
			Id: 0,
		})
	});
	const ruleFormRef = ref();
	const newFormInline = ref(props.formInline);
	function getRef() {
		return ruleFormRef.value;
	}
	defineExpose({ getRef });
  const router = useRouter();
  onMounted(async()=> {
    // if(router.currentRoute.value?.query) {
    //   if(router.currentRoute.value?.query?.index === '1') {
    //     newFormInline.value.title ='创建订单'
    //   } else if(router.currentRoute.value?.query?.index === '1') {
    //     newFormInline.value.title ='编辑订单'
    //   }

    // }
    if(newFormInline.value.title ==='创建订单'){
      newFormInline.value.orderNo = 'P' + dayjs().format('YYYYMMDDHHmmss')
      newFormInline.value.orderDate = dayjs().format('YYYY-MM-DD HH:mm:ss')
    }
    if(newFormInline.value.title === '创建订单' || newFormInline.value.title === '编辑订单') {
      const res: any = await projectSelectApi({type: 'all'});
      // let statusArr = []
      // for (let item of res?.result) {
      //   if(item.status === 1) {
      //     statusArr.push(item)
      //   }
      // }
      newFormInline.value.projectSelect = res?.result;
      // 获取供应商
      const supplier: any = await supplierSelectApi();
      newFormInline.value.supplierList = supplier?.result ?? [];
      //获取人员
      const user: any = await userSelectApi();
      newFormInline.value.userList = user?.result ?? [];
      // 配件
      const part: any = await partSelectApi();
      newFormInline.value.partList = part?.result ?? [];
      // 设备
      const dev: any = await productSelectApi();
      newFormInline.value.deviceList = dev?.result ?? [];
      // 公司
      const company: any = await companySelectApi();
      newFormInline.value.companyList = company?.result ?? [];
      // 分类
      const category: any = await categorySelectApi({type: 3});
      newFormInline.value.categoryList = category?.result ?? [];
      getStoreData()
    }
  })
  const addGoodsChange = () => {
    newFormInline.value.productList.push({
      productName: null,productNo: null, productSpec: null,productUnit: null,number: null,price: null,amount: null,
      categoryId: null,projectId: null,remarks: '',storeId: 1, deviceId: null, accessoriesId: null
    })
  }
  const deleteGoodsChange = (index?: number) => {
    newFormInline.value.productList.splice(index, 1)
  }
  // 获取仓库
  const storeOptions = ref()
  const getStoreData = async(val?: string) => {
    const res: any = await storeListApi({name: val});
    storeOptions.value = res?.result?.list ?? []
  }
  // 总额改变后，单价改变
  const amountChange = (row: any) => {
    row.price = (row.amount / row.number).toFixed(8)

  }
  // 数量合计
  const numberChange = (row?: any) => {

    if(row.number && row.price) {
      row.amount = (row.number * row.price).toFixed(8)
    }
  }
  // 价格
  const priceChange = (row?: any) => {
    if(row.number && row.price) {
      row.amount = (row.number * row.price).toFixed(8)
    }
  }
  //合计
  const getSummaries = (param) => {
    const { columns, data } = param;
    const sums = [];
    columns.forEach((column, index) => {
      if (index === 0) {
        sums[index] = '合计';
        return;
      }
      const values = data.map(item => Number(item[column.property]));
      if (!values.every(value => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr);
          if(column.property === 'number') {
            return prev + curr;
          } else if(column.property === 'amount') {
            return prev + curr;
          } else {
            return '--'
          }
        }, 0);
        sums[index] += '';
      } else {
        sums[index] = '--';
      }
    });
    return sums;
  };
</script>

<template>
	<el-form ref="ruleFormRef" :model="newFormInline" :rules="formRules" label-width="auto" class="mb-[20px]">
    <el-row :gutter="20" v-if="newFormInline.title === '创建订单' || newFormInline.title === '编辑订单'">
      <el-col :xs="12" :sm="8" :md="8" :lg="6" :xl="4">
        <el-form-item label="入库单号" prop="orderNo">
        	<el-input v-model="newFormInline.orderNo" clearable placeholder="请输入" />
        </el-form-item>
      </el-col>
      <el-col :xs="12" :sm="8" :md="8" :lg="6" :xl="4">
        <el-form-item label="入库单日期" prop="orderDate">
        	<el-date-picker
        	  v-model="newFormInline.orderDate"
        	  type="date"
        	  placeholder="请选择"
        	  format="YYYY-MM-DD"
        	  value-format="YYYY-MM-DD"
        	/>
        </el-form-item>
      </el-col>
      <el-col :xs="12" :sm="8" :md="8" :lg="6" :xl="4">
        <el-form-item label="公司" prop="companyId">
          <el-select
            v-model="newFormInline.companyId"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in newFormInline.companyList"
              :key="item.companyId"
              :label="item.companyName"
              :value="item.companyId"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :xs="12" :sm="8" :md="8" :lg="6" :xl="4">
        <el-form-item label="单据类型" prop="orderType">
        	<el-select v-model="newFormInline.orderType" clearable placeholder="请选择">
            <el-option label="采购入库" :value="1" />
            <el-option label="产品入库" :value="2" />
            <el-option label="产品退库" :value="3" />
            <el-option label="其他入库" :value="4" />
            <el-option label="生产退料" :value="5" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :xs="12" :sm="8" :md="8" :lg="6" :xl="4">
        <el-form-item label="供应商" prop="supplierId">
          <el-select
            v-model="newFormInline.supplierId"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in newFormInline.supplierList"
              :key="item.supplierId"
              :label="item.supplierName"
              :value="item.supplierId"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :xs="12" :sm="8" :md="8" :lg="6" :xl="4">
        <el-form-item label="入单员" prop="keyboarder">
          <el-select
            v-model="newFormInline.keyboarder"
            placeholder="请选择"
            clearable
            filterable
          >
            <el-option
              v-for="item in newFormInline.userList"
              :key="item.name"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :xs="12" :sm="8" :md="8" :lg="6" :xl="4">
        <el-form-item label="主管" prop="supervisor">
          <el-select
            v-model="newFormInline.supervisor"
            placeholder="请选择"
            clearable
            filterable
          >
            <el-option
              v-for="item in newFormInline.userList"
              :key="item.name"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :xs="12" :sm="8" :md="8" :lg="6" :xl="4">
        <el-form-item label="经办人" prop="transactor">
          <el-select
            v-model="newFormInline.transactor"
            placeholder="请选择"
            clearable
            filterable
          >
            <el-option
              v-for="item in newFormInline.userList"
              :key="item.name"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :xs="12" :sm="8" :md="8" :lg="6" :xl="4">
        <el-form-item label="执行入库" prop="updateToStore">
          <el-radio-group v-model="newFormInline.updateToStore">
            <el-radio :value="0">否</el-radio>
            <el-radio :value="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :xs="24" :sm="24" :md="24" :lg="18" :xl="12">
        <el-form-item label="备注" prop="remarks">
        	<el-input v-model="newFormInline.remarks" clearable type="textarea" :rows="1" placeholder="请输入" />
        </el-form-item>
      </el-col>

      <el-table :data="newFormInline.productList" border style="width: 100%" :header-cell-style="{background: '#e3e3e3',
        color: 'var(--el-text-color-primary)'}" :summary-method="getSummaries" show-summary>
        <el-table-column prop="productName" label="产品名称" min-width="150">
          <template #default="scope">
            <el-input v-model="scope.row.productName" placeholder="请输入" />
          </template>
        </el-table-column>
        <el-table-column prop="productNo" label="产品编号" min-width="150">
          <template #default="scope">
            <el-input v-model="scope.row.productNo" placeholder="请输入" />
          </template>
        </el-table-column>
        <el-table-column prop="productSpec" label="规格" min-width="180">
          <template #default="scope">
            <el-input v-model="scope.row.productSpec" placeholder="请输入" />
          </template>
        </el-table-column>
        <el-table-column prop="productUnit" label="单位" min-width="90">
          <template #default="scope">
            <el-input v-model="scope.row.productUnit" placeholder="请输入" />
          </template>
        </el-table-column>
        <el-table-column prop="number" label="数量" min-width="120">
          <template #default="scope">
            <el-input v-model="scope.row.number" placeholder="请输入" type="number" class="no_number" @blur="numberChange(scope.row)"/>
            <!-- <el-input-number
              v-model="scope.row.number"
              :min="0"
              :precision="2"
              :controls="false"
              class="!w-full"
              align="left"
              placeholder="请输入"
            /> -->
          </template>
        </el-table-column>
        <el-table-column prop="price" label="产品单价" min-width="120">
          <template #default="scope">
            <!-- <el-input-number
              v-model="scope.row.price"
              :min="0"
              :precision="4"
              :controls="false"
              class="!w-full"
              align="left"
              placeholder="请输入"
            /> -->
            <el-input v-model="scope.row.price" placeholder="请输入" type="number" class="no_number" @blur="priceChange(scope.row)"/>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="总金额" min-width="120">
          <template #default="scope">
            <!-- <el-input-number
              v-model="scope.row.amount"
              :min="0"
              :precision="4"
              :controls="false"
              class="!w-full"
              align="left"
              placeholder="请输入"
              @blur="amountChange(scope.row)"
            /> -->
            <el-input v-model="scope.row.amount" placeholder="请输入" type="number" class="no_number" @blur="amountChange(scope.row)"/>
          </template>
        </el-table-column>
        <el-table-column prop="categoryId" label="分类" min-width="120">
          <template #default="scope">
            <el-select
              v-model="scope.row.categoryId"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="item in newFormInline.categoryList"
                :key="item.categoryId"
                :label="item.name"
                :value="item.categoryId"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="projectId" label="项目" min-width="150">
          <template #default="scope">
            <el-select
              v-model="scope.row.projectId"
              placeholder="请选择"
              clearable
              filterable
            >
              <el-option
                v-for="item in newFormInline.projectSelect"
                :key="item.projectId"
                :label="item.projectName"
                :value="item.projectId"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="storeId" label="仓库" min-width="150">
          <template #default="scope">
            <!-- <el-input v-model="scope.row.storeId" placeholder="请输入" /> -->
            <el-select
              v-model="scope.row.storeId"
              placeholder="请选择"
              clearable
              filterable
              class="!w-full"
              :filter-method="getStoreData"
              disabled
            >
              <el-option
                v-for="item in storeOptions"
                :key="item.storeId"
                :label="item.name"
                :value="item.storeId"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="deviceId" label="设备" min-width="160">
          <template #default="scope">
            <!-- <el-input v-model="scope.row.deviceId" placeholder="请输入" /> -->
            <el-select
              v-model="scope.row.deviceId"
              placeholder="请选择"
              clearable
              filterable
              multiple
            >
              <el-option
                v-for="item in newFormInline.deviceList"
                :key="item.id"
                :label="item.deviceName"
                :value="item.id"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="accessoriesId" label="配件" min-width="160">
          <template #default="scope">
            <el-select
              v-model="scope.row.accessoriesId"
              placeholder="请选择"
              clearable
              filterable
              multiple
            >
              <el-option
                v-for="item in newFormInline.partList"
                :key="item.partId"
                :label="item.partName"
                :value="item.partId"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注" min-width="120">
          <template #default="scope">
            <el-input v-model="scope.row.remarks" type="textarea" :rows="2" placeholder="请输入" />
          </template>
        </el-table-column>
        <el-table-column prop=" " label="操作" width="70" fixed="right">
          <template #default="{row, $index}">
            <el-button type="primary" v-if="$index === 0" class="!w-[40px]" @click="addGoodsChange">+</el-button>
            <el-button type="danger" v-else class="!w-[40px]" @click="deleteGoodsChange($index)">-</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <template v-if="newFormInline.title === '订单详情'">
      <div class="no_buttom mb-[10px]">

        <el-row :gutter="10">
          <el-col :xs="12" :sm="8" :md="8" :lg="6" :xl="4">
            <el-form-item label="入库单号">
            	<span>{{newFormInline.detaileInfo.orderNo}}</span>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="8" :md="8" :lg="6" :xl="4">
            <el-form-item label="公司">
            	<span>{{newFormInline.detaileInfo.company?.companyName || '--'}}</span>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="8" :md="8" :lg="6" :xl="4">
            <el-form-item label="供应商">
            	<span>{{newFormInline.detaileInfo.supplier?.supplierName || '--'}}</span>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="8" :md="8" :lg="6" :xl="4">
            <el-form-item label="单据类型">
            	<span>{{newFormInline.detaileInfo.orderTypeName}}</span>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="8" :md="8" :lg="6" :xl="4">
            <el-form-item label="入单员">
            	<span>{{newFormInline.detaileInfo.keyboarder}}</span>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="8" :md="8" :lg="6" :xl="4">
            <el-form-item label="主管">
            	<span>{{newFormInline.detaileInfo.supervisor}}</span>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="8" :md="8" :lg="6" :xl="4">
            <el-form-item label="经办人">
            	<span>{{newFormInline.detaileInfo.transactor}}</span>
            </el-form-item>
          </el-col>
        </el-row>

      </div>

      <pure-table ref="tableRef" align-whole="center" showOverflowTooltip table-layout="auto" border  :summary-method="getSummaries" show-summary
        :adaptiveConfig="{ offsetBottom: 108 }" :data="newFormInline.detaileInfo.orderProducts" :columns="expandColumns"
        :paginationSmall="true" :header-cell-style="{background: '#e3e3e3',
        color: 'var(--el-text-color-primary)'}">
      </pure-table>
    </template>
	</el-form>
</template>
<style scoped>

  :deep(.el-input-number.is-without-controls .el-input__wrapper) {
    padding-left: 11px;
    padding-right: 11px;
  }
  :deep(.el-input-number .el-input__inner) {
    text-align: left;
  }
  :deep(.no_buttom .el-form-item) {
    margin-bottom: 0px;
  }
</style>
